﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DatabaseSync
{
    public partial class Form1 : Form
    {
        private static string TempDirectory = "temp";
        public Form1()
        {
            InitializeComponent();
        }

        private void Test()
        {
            MySqlConnection dbConnection = new MySqlConnection("");
            MySqlBulkLoader loader = new MySqlBulkLoader(dbConnection);
        }



        private void button1_Click(object sender, EventArgs e)
        {
            Stopwatch watch = Stopwatch.StartNew();
            StringBuilder sb = new StringBuilder();
            var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345678900000000000000\r\n";
            for (int i = 0; i < 10000000; i++)
            {
                sb.Append(str);
            }
            watch.Stop();
            Console.WriteLine("a=" + watch.ElapsedMilliseconds); ;
            watch.Reset();
            watch.Start();
            using (FileStream fs = new FileStream("a.txt", FileMode.Create))
            {
                var data = Encoding.UTF8.GetBytes(sb.ToString());

                fs.Write(data, 0, data.Length);
            }
            watch.Stop();
            Console.WriteLine("b=" + watch.ElapsedMilliseconds);

            watch.Reset();
            watch.Start();
            File.WriteAllText("c.txt", sb.ToString());
            watch.Stop();
            Console.WriteLine("c=" + watch.ElapsedMilliseconds);
        }

        private DataTable GetDataTable(MySqlConnection connection, string tableName, int skipCount, int maxCount = 1000)
        {
            string sql = $"select * from {tableName}";
            
        }

        /// <summary>
        /// 批量插入数据
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        private int BulkInsert(MySqlConnection connection, DataTable table)
        {
            if (string.IsNullOrEmpty(table.TableName))
            {
                throw new Exception("DataTable的TableName属性没有设置表名");
            }

            if (table.Rows.Count == 0)
            {
                return 0;
            }
            int insertCount = 0;

            string tableCsvFile = Path.Combine(TempDirectory, table.TableName + ".csv");
            DataTable2Csv(table, tableCsvFile);

            MySqlTransaction tran = null;
            try
            {
                tran = connection.BeginTransaction();
                MySqlBulkLoader bulk = new MySqlBulkLoader(connection)
                {
                    FieldTerminator = ",",
                    FieldQuotationCharacter = '"',
                    EscapeCharacter = '"',
                    LineTerminator = "\r\n",
                    FileName = tableCsvFile,
                    NumberOfLinesToSkip = 0,
                    TableName = table.TableName,
                };
                bulk.Columns.AddRange(table.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToList());
                insertCount = bulk.Load();

                tran.Commit();
            }
            catch (Exception ex)
            {
                if (tran != null)
                {
                    tran.Rollback();
                }
                throw ex;
            }

            File.Delete(tableCsvFile);
            return insertCount;
        }


        /// <summary>
        /// DataTable 转成 csv 文件
        /// </summary>
        /// <param name="table"></param>
        /// <param name="csvFile"></param>
        private void DataTable2Csv(DataTable table, string csvFile)
        {
            StringBuilder sb = new StringBuilder();

            DataColumn colum;
            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    colum = table.Columns[i];
                    if (i != 0) sb.Append(",");
                    if (colum.DataType == typeof(string) && row[colum].ToString().Contains(","))
                    {
                        sb.Append("\"" + row[colum].ToString().Replace("\"", "\"\"") + "\"");
                    }
                    else sb.Append(row[colum].ToString());
                }
                sb.AppendLine();
            }

            var csvData = sb.ToString();
            using (FileStream fs = new FileStream(csvFile, FileMode.Create))
            {
                var data = Encoding.UTF8.GetBytes(csvData);
                fs.Write(data, 0, data.Length);
            }
        }


    }
}
